package com.dd.cloud.common.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonStreamContext;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.dd.cloud.common.annotate.FileSuffix;
import com.dd.cloud.common.config.common.SpringContextJobUtil;
import com.dd.cloud.common.config.obs.PathProperties;
import com.dd.cloud.common.utils.FileUrlPrefixUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Objects;

/**
* @Author: czg
* @Description: 文件地址路径注解字段自定义序列化
* @DateTime: 2022/9/21 18:04
* @Params: 
* @Return 
*/
@Slf4j
public class FileSuffixSerializer extends JsonSerializer<Object> {

    @Override
    public void serialize(Object value, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException {
        if (Objects.isNull(value)) {
            return;
        }
        //log.info("自定义注解序列化地址");
        JsonStreamContext outputContext = jsonGenerator.getOutputContext();
        // 获取当前class对象
        Class<?> clazz = outputContext.getCurrentValue().getClass();
        // 获取当前属性名
        String fieldName = outputContext.getCurrentName();
        // 获取当前属性的field
        Field field = FieldUtils.getDeclaredField(clazz, fieldName, true);
        // 获取当前属性的注解
        FileSuffix annotation = field.getAnnotation(FileSuffix.class);
        if (annotation == null) {
            jsonGenerator.writeObject(value);
            return;
        }
        PathProperties path = (PathProperties) SpringContextJobUtil.getBean("pathProperties");
        FileUrlPrefixUtils prefixUtils = new FileUrlPrefixUtils(path.getImageServer(), path.getAgentServer());
        Object fileValue =  fileServer(prefixUtils.imageServer, prefixUtils.agentServer, annotation, value);
        jsonGenerator.writeObject(fileValue);
    }


    /**
     * 文件添加或去除文件服务器路径
     *
     * @param fileSuffix 服务器路径
     * @param value      字段
     * @return
     */
    public Object fileServer(String server, String agentServer, FileSuffix fileSuffix, Object value) {
        String valueStr = (String) value;
        if (StringUtils.isBlank(valueStr)) {
            return valueStr;
        }
        boolean head = fileSuffix.head();
        FileUrlPrefixUtils prefix = new FileUrlPrefixUtils(server, agentServer);
        if (head) {
            if (!valueStr.startsWith("http")) {
                return prefix.addImageServer(valueStr);
            }
        } else {
            return prefix.deleteImageServer(valueStr);
        }
        return valueStr;
    }
}
